package com.fog.judge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fog.judge.common.UserContext;
import com.fog.judge.dto.CourseTeacherDto;
import com.fog.judge.entity.Course;
import com.fog.judge.entity.SelectCourse;
import com.fog.judge.entity.User;
import com.fog.judge.mapper.CourseMapper;
import com.fog.judge.service.CourseService;
import com.fog.judge.service.SelectCourseService;
import com.fog.judge.service.TeacherService;
import com.fog.judge.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements CourseService {


    @Resource
    private UserService userService;

    @Resource
    private CourseService courseService;

    @Resource
    private SelectCourseService selectCourseService;

    @Resource
    private TeacherService teacherService;
    @Override
    @Transactional
    public Page<CourseTeacherDto> selectSearch(int page, int pageSize) {
        // 获取学生可以评价老师以及课程名称列表
        int userId = UserContext.getUserId();

        Page<Course> pageInfo = new Page<>(page, pageSize);

        Page<CourseTeacherDto> courseDtoPage = new Page<>();

        QueryWrapper<Course> courseQueryWrapper = new QueryWrapper<>();

        courseQueryWrapper.orderByDesc("id");

        int id = UserContext.getUserId();

        courseQueryWrapper.inSql("id","select course_id from select_course where student_id = "+ id);

        page(pageInfo, courseQueryWrapper);

        BeanUtils.copyProperties(pageInfo, courseDtoPage);

        List<Course> records = pageInfo.getRecords();

        List<CourseTeacherDto> recordsDto = records.stream().map((item)->{
            CourseTeacherDto courseDto = new CourseTeacherDto();
            BeanUtils.copyProperties(item, courseDto);
            String teacherName = userService.getById(teacherService.getById(item.getTeacherId()).getUserId()).getFullName();
            courseDto.setTeacherName(teacherName);
            return courseDto;
        }).collect(Collectors.toList());
        courseDtoPage.setRecords(recordsDto);
        return courseDtoPage;
    }
}
